//
//  BankCardManageViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "BankCardManageViewController.h"
#import "SettingContentTableViewCell.h"
#import "SettingArrowTableViewCell.h"
#import "OpenAccountViewController.h"
#import "UntieCardViewController.h"
#import "ChangeCardPhoneViewController.h"
#import "BindBankCardViewController.h"

@interface BankCardManageViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * haveAccountArr;//已开户
@property (nonatomic, strong)NSMutableArray * noAccountArr;//未开户
@property (nonatomic, strong)NSMutableArray * unLockCardArr;//已开户未绑卡开户
@end

@implementation BankCardManageViewController(networking)
//开户
- (void)openAccountData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/kaihuAdd"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    OpenAccountViewController * vc = [[OpenAccountViewController alloc] init];
                    vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                    vc.bankNeedInfoDic = @{
                                           @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                           @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                           @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                           @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                           @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                    vc.sessionID = jsonData[@"session"];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    NSLog(@"无内容");
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
//解绑银行卡
- (void)untieAccountData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/ojbk"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    UntieCardViewController * vc = [[UntieCardViewController alloc] init];
                    vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                    vc.bankNeedInfoDic = @{
                                           @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                           @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                           @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                           @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                           @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                    vc.sessionID = jsonData[@"session"];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    NSLog(@"无内容");
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
            
        }
    }];
}
//修改银行卡预留手机号
- (void)changeCardPhoneData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/banktele"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    ChangeCardPhoneViewController * vc = [[ChangeCardPhoneViewController alloc] init];
                    vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                    vc.bankNeedInfoDic = @{
                                           @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                           @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                           @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                           @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                           @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                    vc.sessionID = jsonData[@"session"];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    NSLog(@"无内容");
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
//绑定银行卡
- (void)bindBankCardData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/bkcz"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    BindBankCardViewController * vc = [[BindBankCardViewController alloc] init];
                    vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                    vc.bankNeedInfoDic = @{
                                           @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                           @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                           @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                           @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                           @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                    vc.sessionID = jsonData[@"session"];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    NSLog(@"无内容");
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end
@implementation BankCardManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"银行卡管理";
    self.view.backgroundColor = [UIColor whiteColor];
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
}
#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SettingArrowTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SettingArrowTableViewCell class])];
        [_tableView registerClass:[SettingContentTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SettingContentTableViewCell class])];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = getColor(grayBGColor);
    }return _tableView;
}
- (NSMutableArray *)haveAccountArr{
    if (!_haveAccountArr) {
        _haveAccountArr = @[@{@"title":@"解绑银行卡"},
                            @{@"title":@"修改银行卡预留手机号"}].mutableCopy;
    }return _haveAccountArr;
}
- (NSMutableArray *)noAccountArr{
    if (!_noAccountArr) {
        _noAccountArr = @[@{@"title":@"开户陕坝", @"content":@"未开户"}].mutableCopy;
    }return _noAccountArr;
}
- (NSMutableArray *)unLockCardArr{
    if (!_unLockCardArr) {
        _unLockCardArr = @[@{@"title":@"绑定银行卡"}].mutableCopy;
    }return _unLockCardArr;
}

#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    SettingArrowTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SettingArrowTableViewCell class]) forIndexPath:indexPath];
//    cell.model = self.haveAccountArr[indexPath.row];
//    if (indexPath.row == self.haveAccountArr.count - 1) {
//        cell.lineView.hidden = YES;
//    }
    
    SettingContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SettingContentTableViewCell class]) forIndexPath:indexPath];
    if (self.ifHaveOpenAccount == 0) {
        cell.model = self.noAccountArr[indexPath.row];
    }
    if (self.ifHaveOpenAccount == 1) {
        cell.model = self.haveAccountArr[indexPath.row];
    }
    if (self.ifHaveOpenAccount == 2) {
        cell.model = self.unLockCardArr[indexPath.row];
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.ifHaveOpenAccount == 0) {
        return self.noAccountArr.count;
    }else if (self.ifHaveOpenAccount == 1){
        return self.haveAccountArr.count;
    }else{
        return self.unLockCardArr.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56/WIDTH_6_SCALE;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SettingContentTableViewCell * cell = (SettingContentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.model[@"title"] isEqualToString:@"解绑银行卡"]) {
        [self untieAccountData];
    }
    if ([cell.model[@"title"] isEqualToString:@"修改银行卡预留手机号"]) {
        [self changeCardPhoneData];
    }
    if ([cell.model[@"title"] isEqualToString:@"开户陕坝"]) {
        [self openAccountData];
    }
    if ([cell.model[@"title"] isEqualToString:@"绑定银行卡"]) {
        [self bindBankCardData];
    }
    
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
